const labelService = require('../service/label.service');

const verifyLabelExists = async (ctx, next) => {
    try {
        const {
            labels
        } = ctx.request.body;   //[ '全栈', '爱情', '友情' ]
        // console.log(labels);
        const newlabels = [];
        for (let name of labels) {
            const isExist = await labelService.isExistLabel(name);
            // console.log(isExist);
            const label = {name};
            if (!isExist) {
                const result = await labelService.create(name);
                // console.log(result);
                label.id = result.insertId;
            } else {
                label.id = isExist.id;
            }
            newlabels.push(label);
        }
        // console.log(newlabels);
        ctx.labels = newlabels; 
        await next();
    } catch (err) {
        console.log(err);
    }
}

module.exports = {
    verifyLabelExists
}